import { useSyncExternalStore } from "react"
export function useStorage<T>(key: string, initialValue: T) {
  // 订阅者
  const subscribe = (callback: () => void) => {
    // 订阅浏览器API
    window.addEventListener('storage', callback)
    return () => {
      // 返回取消订阅
      window.removeEventListener('storage', callback)
    }
  }

  const getSnapshot = () => {
    const item = window.localStorage.getItem(key)
    return item ? JSON.parse(item) : initialValue
  }
  const state = useSyncExternalStore(subscribe, getSnapshot)

  const update = (value: T) => {
    window.localStorage.setItem(key, JSON.stringify(value))
    window.dispatchEvent(new StorageEvent('storage')) // 手动触发storage事件
  }
  return [state, update]
}